package io.xccit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.xccit.clients.IProductClients;
import io.xccit.mapper.ICollectMapper;
import io.xccit.pojo.collect.Collect;
import io.xccit.pojo.param.ProductCollectParam;
import io.xccit.result.AjaxResult;
import io.xccit.service.ICollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CH_ywx
 * @date 2023-09-14
 * @description
 */
@Slf4j
@Service
public class CollectServiceImpl extends ServiceImpl<ICollectMapper, Collect> implements ICollectService {

    @Autowired
    private ICollectMapper collectMapper;

    @Autowired
    private IProductClients productClients;

    /**
     * @param collect
     * @return
     */
    @Override
    public AjaxResult saveCollect(Collect collect) {
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collect::getUserId,collect.getUserId());
        wrapper.eq(Collect::getProductId,collect.getProductId());
        Long rows = collectMapper.selectCount(wrapper);
        if (rows > 0){
            return AjaxResult.fail("已收藏该商品,无需再次收藏");
        }
        collect.setCollectTime(System.currentTimeMillis());
        collectMapper.insert(collect);
        return AjaxResult.success("收藏成功");
    }

    /**
     * 根据userId获取收藏商品信息
     *
     * @param userId
     * @return
     */
    @Override
    public AjaxResult getCollectList(Integer userId) {
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collect::getUserId,userId);
        wrapper.select(Collect::getProductId);
        List<Object> productIds = collectMapper.selectObjs(wrapper);
        List<Integer> ids = new ArrayList<>();
        for (Object productId : productIds) {
            ids.add((Integer) productId);
        }
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(ids);
        //TODO 远程调用
        AjaxResult products = productClients.getProductByIds(productCollectParam);
        return products;
    }

    /**
     * 删除收藏
     *
     * @param collect
     * @return
     */
    @Override
    public AjaxResult removeCollect(Collect collect) {
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",collect.getUserId());
        wrapper.eq("product_id",collect.getProductId());
        int delete = collectMapper.delete(wrapper);
        if (delete <= 0){
            AjaxResult.builder().code(201).message("移除失败,请检查参数").data(null).build();
        }
        return AjaxResult.build(200,"移除成功",null);
    }
}
